package cn.xtits.xtf.common.spring.db.readwrite;

import javax.sql.DataSource;


public class DynamicReadWriterDataSourceHolder {
    private static final String MASTER = "master";
    private static final String SLAVE = "slave";

    /**
     * 主或者备,外部动态切换
     */
    private static final ThreadLocal<String> dataSource = new ThreadLocal<String>();

    /**
     * 主库
     */
    private static final ThreadLocal<DataSource> masterDatasource = new ThreadLocal<DataSource>();

    /**
     * 备库
     */
    private static final ThreadLocal<DataSource> slaveDatasource = new ThreadLocal<DataSource>();

    /**
     * 设置数据源
     * @param dataSourceKey
     */
    private static void setDataSource(String dataSourceKey) {
        dataSource.set(dataSourceKey);
    }

    /**
     * 获取数据源
     * @return
     */
    private static String getDataSource() {
        return dataSource.get();
    }

    /**
     * 设置为主
     */
    public static void setMaster() {
        setDataSource(MASTER);
    }

    /**
     * 设置为备
     */
    public static void setSlave() {
        setDataSource(SLAVE);
    }

    /**
     * 设置为主
     */
    public static void setMaster(DataSource dataSource) {
        masterDatasource.set(dataSource);
    }

    /**
     * 设置为备
     */
    public static void setSlave(DataSource dataSource) {
        slaveDatasource.set(dataSource);
    }

    /**
     * 是否是主库
     * @return
     */
    public static boolean isMaster() {
        return getDataSource() == MASTER;
    }

    /**
     * 是否是备库
     * @return
     */
    public static boolean isSlave() {
        return getDataSource() == SLAVE;
    }

    public static void clear() {
        dataSource.remove();
        masterDatasource.remove();;
        slaveDatasource.remove();
    }





}
